<template>
  <el-card class="page-container">
    <div v-if="loading" class="loading-container">
      <el-icon class="loading-icon"><Loading /></el-icon>
    </div>
    <div v-else>
      <!-- 商家信息卡片 -->
      <div class="merchant-info-card">
        <div class="avatar-section">
          <img
              :src="curMerchant.avatarUrl || '/default-avatar.png'"
              alt="商家头像"
              class="merchant-avatar"
          />
          <div class="merchant-name">
            <h2>{{ curMerchant.nickname || '未设置昵称' }}</h2>
            <div class="status-badge" :class="curMerchant.status === 1 ? 'status-normal' : 'status-banned'">
              {{ accountStatus[curMerchant.status] }}
            </div>
          </div>
        </div>

        <el-descriptions title="账户信息" border class="info-descriptions">
          <el-descriptions-item label="账号" align="center">{{ curMerchant.username }}</el-descriptions-item>
          <el-descriptions-item label="注册时间" align="center">{{ curMerchant.registeredAt || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="电话" align="center">{{ curMerchant.phone || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="邮箱" align="center">{{ curMerchant.email || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="微信" align="center">{{ curMerchant.wechatId || '未设置' }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <el-divider class="custom-divider">
        <el-icon class="divider-icon"><Message /></el-icon>
      </el-divider>

      <div class="edit-merchant-info-btn-div">
        <el-button
            class="edit-merchant-info-btn"
            type="primary"
            @click="drawerVisible = true"
        >
          <span>
            <el-icon><Edit /></el-icon>
            编辑个人信息
          </span>
        </el-button>
      </div>
    </div>

    <!-- 编辑信息抽屉 -->
    <el-drawer
        v-model="drawerVisible"
        :direction="direction"
        :before-close="() => { drawerVisible.value = false; }"
        class="custom-drawer"
    >
      <template #header>
        <h4 class="drawer-title">编辑个人信息</h4>
      </template>
      <template #default>
        <el-form label-width="80px" class="edit-form">
          <el-form-item label="照片" class="form-item">
            <el-upload
                class="avatar-uploader"
                action="/api/file/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
            >
              <img
                  v-if="imageUrl || curMerchantInfo.avatarUrl"
                  :src="imageUrl || curMerchantInfo.avatarUrl"
                  class="avatar"
                  alt=""
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="账号" class="form-item">
            <el-input v-model="curMerchantInfo.username" disabled>
              <template #append>
                <el-button
                    @click="copyToClipboard"
                    class="copy-btn"
                >
                  复制账号
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="昵称" class="form-item">
            <el-input
                v-model="curMerchantInfo.nickname"
                placeholder="请输入昵称"
                class="form-input"
            />
          </el-form-item>
          <el-form-item label="电话" class="form-item">
            <el-input
                v-model="curMerchantInfo.phone"
                placeholder="请输入电话号码"
                class="form-input"
            />
          </el-form-item>
          <el-form-item label="邮箱" class="form-item">
            <el-input
                v-model="curMerchantInfo.email"
                placeholder="请输入邮箱地址"
                class="form-input"
                type="email"
            />
          </el-form-item>
          <el-form-item label="微信" class="form-item">
            <el-input
                v-model="curMerchantInfo.wechatId"
                placeholder="请输入微信号"
                class="form-input"
            />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="drawer-footer">
          <el-button
              @click="cancelClick"
              class="cancel-btn"
          >
            取消
          </el-button>
          <el-button
              type="primary"
              @click="confirmClick"
              class="confirm-btn"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>

<script setup>
import { Edit, Message, Plus, StarFilled, Loading } from "@element-plus/icons-vue";
import { ref } from "vue";
import { onBeforeRouteUpdate, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCurMerchant, saveUpdatedMerchant } from "@/api/merchant";

const drawerVisible = ref(false);
const direction = ref("rtl");
const router = useRouter();
const curMerchant = ref({});
const curMerchantInfo = ref({});
const accountStatus = ref(["封禁", "正常"]);
const imageUrl = ref("");
const loading = ref(false); // 添加加载状态

// 获取当前商家信息
const getCurMerchantInfo = () => {
  loading.value = true; // 开始加载
  getCurMerchant()
      .then((res) => {
        if (res.data) {
          curMerchant.value = res.data;
          curMerchantInfo.value = JSON.parse(JSON.stringify(curMerchant.value));
          imageUrl.value = curMerchantInfo.value.avatarUrl;
        } else {
          ElMessageBox.alert("请先登录商家账号", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          }).then(() => {
            router.push({ path: "/merchantLoginPage" });
          });
        }
      })
      .finally(() => {
        loading.value = false; // 加载完成
      });
};
getCurMerchantInfo();

function cancelClick() {
  drawerVisible.value = false;
}

const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  curMerchantInfo.value.avatarUrl = response.data.url;
};

// 确认修改商家信息
function confirmClick() {
  ElMessageBox.confirm("是否确定修改信息？", "提示")
      .then(() => {
        curMerchant.value = { ...curMerchant.value, ...curMerchantInfo.value };
        drawerVisible.value = false;
        loading.value = true; // 开始加载
        saveUpdatedMerchant(curMerchant.value)
            .then((res) => {
              if (res.data) {
                ElMessage({
                  type: "success",
                  message: "修改成功",
                });
                getCurMerchantInfo();
              }
            })
            .finally(() => {
              loading.value = false; // 加载完成
            });
      })
      .catch(() => {});
}

// 复制方法
const copyToClipboard = () => {
  navigator.clipboard.writeText(curMerchantInfo.value.username)
      .then(() => {
        ElMessage.success("复制成功");
      })
      .catch(() => {
        const textarea = document.createElement("textarea");
        textarea.value = curMerchantInfo.value.username;
        document.body.appendChild(textarea);
        textarea.select();
        document.body.removeChild(textarea);
        ElMessage.success("复制成功");
      });
};

onBeforeRouteUpdate((to, from) => {
  drawerVisible.value = false;
});
</script>

<style scoped lang="scss">
// 颜色变量（统一为系统主色调）
$primary: #1E40AF;
$primary-light: rgba(30, 64, 175, 0.1);
$primary-hover: #3B82F6;
$success: #10B981;
$danger: #EF4444;
$light-gray: #F8FAFC;
$border-color: #E2E8F0;
$text-primary: #1E293B;
$transition: all 0.3s ease;

.page-container {
  max-width: 900px;
  margin: 20px auto;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  transition: $transition;

  &:hover {
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;

  .loading-icon {
    font-size: 40px;
    color: $primary;
    animation: spin 1.5s linear infinite;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.merchant-info-card {
  padding: 20px 0;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid $border-color;

  .merchant-avatar {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
    border: 4px solid $light-gray;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
    transition: $transition;

    &:hover {
      transform: scale(1.05) rotate(2deg);
    }
  }

  .merchant-name {
    display: flex;
    align-items: center;
    gap: 15px;

    h2 {
      margin: 0;
      font-size: 24px;
      color: $text-primary;
    }

    .status-badge {
      padding: 4px 12px;
      border-radius: 20px;
      font-size: 14px;
      font-weight: 500;
    }

    .status-normal {
      background-color: rgba(16, 185, 129, 0.1);
      color: $success;
    }

    .status-banned {
      background-color: rgba(239, 68, 68, 0.1);
      color: $danger;
    }
  }
}

.info-descriptions {
  background-color: $light-gray;
  border-radius: 8px;
  overflow: hidden;

  ::v-deep .el-descriptions__title {
    color: $primary;
    font-size: 18px;
    padding: 15px 20px;
    background-color: rgba(30, 64, 175, 0.05);
    margin-bottom: 0;
  }

  ::v-deep .el-descriptions__body {
    padding: 20px;
  }

  ::v-deep .el-descriptions-item {
    padding: 12px 15px;
    border-color: #e9ecef;

    &:nth-child(odd) {
      background-color: rgba(255, 255, 255, 0.6);
    }
  }

  ::v-deep .el-descriptions-item__label {
    font-weight: 600;
    color: #666;
    background-color: rgba(30, 64, 175, 0.03);
  }
}

.custom-divider {
  margin: 25px 0;

  .divider-icon {
    color: $primary;
    font-size: 18px;
    background-color: white;
    padding: 0 10px;
  }

  ::v-deep .el-divider__line {
    border-color: $border-color;
  }
}

.edit-merchant-info-btn-div {
  text-align: center;
  margin: 30px 0 10px;
}

.edit-merchant-info-btn {
  font-size: 15px;
  padding: 10px 25px;
  border-radius: 8px;
  transition: $transition;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  background-color: $primary;
  border-color: $primary;

  &:hover {
    background-color: $primary-hover;
    border-color: $primary-hover;
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(30, 64, 175, 0.15);
  }

  &:active {
    transform: translateY(0);
  }
}

// 抽屉样式
.custom-drawer {
  ::v-deep .el-drawer__content {
    width: 500px !important;
    max-width: 90vw;
  }

  ::v-deep .el-drawer__header {
    padding: 20px 25px;
    border-bottom: 1px solid $border-color;
  }

  ::v-deep .el-drawer__body {
    padding: 25px;
    overflow-y: auto;
    max-height: calc(100vh - 180px);
  }
}

.drawer-title {
  color: $primary;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;

  &::before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 18px;
    background-color: $primary;
    border-radius: 2px;
  }
}

.edit-form {
  background-color: white;
  padding: 10px;
  border-radius: 8px;
}

.form-item {
  margin-bottom: 20px;
  transition: $transition;

  &:hover {
    transform: translateX(5px);
  }
}

.form-input {
  transition: $transition;

  &:focus-within {
    border-color: $primary;
    box-shadow: 0 0 0 2px rgba(30, 64, 175, 0.2);
  }
}

.avatar-uploader {
  transition: $transition;

  &:hover {
    transform: scale(1.02);
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    border-radius: 8px;
    object-fit: cover;
    border: 1px solid #e5e7eb;
    transition: $transition;

    &:hover {
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    }
  }

  .avatar-uploader-icon {
    width: 178px;
    height: 178px;
    border-radius: 8px;
    background-color: $light-gray;
    transition: $transition;

    &:hover {
      background-color: rgba(30, 64, 175, 0.05);
      color: $primary;
    }
  }
}

.copy-btn {
  transition: $transition;

  &:hover {
    background-color: $light-gray;
    color: $primary;
  }
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 25px;
  border-top: 1px solid $border-color;

  .cancel-btn {
    transition: $transition;

    &:hover {
      background-color: #f5f5f5;
    }
  }

  .confirm-btn {
    background-color: $primary;
    border-color: $primary;
    transition: $transition;

    &:hover {
      background-color: $primary-hover;
      border-color: $primary-hover;
      transform: translateY(-2px);
      box-shadow: 0 3px 10px rgba(30, 64, 175, 0.15);
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .page-container {
    padding: 15px;
    margin: 10px;
  }

  .avatar-section {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .merchant-name {
    flex-direction: column;
    align-items: center;
  }

  .info-descriptions {
    :deep(.el-descriptions-item) {
      width: 100% !important;
      display: flex;
      flex-direction: column;
      align-items: flex-start;

      &:nth-child(odd) {
        background-color: transparent;
      }
    }
  }

  .custom-drawer {
    ::v-deep .el-drawer__content {
      width: 100% !important;
    }
  }
}
</style>